/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.streamline.services.db.transaction;

import javax.transaction.*;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * Transaction implementation.
 */
public class BrillienTransaction implements Transaction {

    private FXID                xID;
    private List<XAResource>    resources;
    private int                 status;

    private List<Connection>    connections;

    {
        resources = new LinkedList<XAResource>();

        connections = new LinkedList<Connection>();
    }

    /**
     * Creates a new BrillienTransaction instance by a FXID instance
     */
    public BrillienTransaction( FXID xID ) {
        this.xID = xID;
        status = Status.STATUS_ACTIVE;
    }

    public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
            try {
                for( XAResource xa : resources )
                    xa.end(xID, XAResource.TMSUCCESS );
            } catch (XAException e) {
                rollback();
                return;
            }

        status = Status.STATUS_PREPARING;
            try {
                for( XAResource xa : resources )
                    xa.prepare( xID );
            } catch (XAException e) {
                rollback();
                return;
            }
        status = Status.STATUS_PREPARED;

        status = Status.STATUS_COMMITTING;
            try {
                for( Connection c : connections )
                    c.commit();
            } catch (SQLException e) {
                rollback();
                return;
            }

            try {
                for( XAResource xa : resources )
                    xa.commit( xID, false );
            } catch (XAException e) {
                rollback();
                return;
            }
        status = Status.STATUS_COMMITTED;
    }

    /**
     * Removes a new Connection as a Resource to this Transaction
     * @param connection connection to be added
     * @return true if the collection of connections changed as a result of the call
     */
    public boolean delistConnection(Connection connection) {
        return connections.remove( connection );
    }

    /**
     * Adds a new Connection as a Resource to this Transaction
     * @param connection connection to be removed
     * @return true if the collection of connections changed as a result of the call
     */
    public boolean enlistConnection(Connection connection) {
        return connections.add( connection );
    }

    public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException {
        try {
            xaResource.forget( xID );
        } catch (XAException e) {
            throw new SystemException( e.getMessage() );
        }
        return resources.remove( xaResource );
    }

    public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException {
        try {
            xaResource.start( xID, XAResource.TMNOFLAGS );
        } catch (XAException e) {
            throw new SystemException( e.getMessage() );
        }
        return resources.add( xaResource );
    }

    public int getStatus() throws SystemException {
        return status;
    }

    public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException {
        throw new SystemException( "No synchronization supported." );
    }

    public void rollback() throws IllegalStateException, SystemException {
        status = Status.STATUS_ROLLING_BACK;
            for( Connection c : connections )
                try {
                    c.rollback();
                } catch (SQLException e) { }

            for( XAResource xa : resources )
                try {
                    xa.rollback( xID );
                } catch (XAException e) {
                    throw new SystemException( e.getMessage() );
                }
        status = Status.STATUS_ROLLEDBACK;
    }

    public void setRollbackOnly() throws IllegalStateException, SystemException {
        throw new SystemException( "No synchronization supported." );
    }

}
